<template>
	<view class="addrepair">
		<view class="ag-topbg"></view>
		<view class="addrepair-card">
			<view class="addrepair-card__head">
				<image src="../../static/img/icon-add-black.png" />
				<text>添加维修信息</text>
			</view>
			<view class="addrepair-card__txtrow" @click.stop="showFaultTree">
				<text style="color: #F0AD4E;">{{selectFaultItemPath||'点击添加故障信息'}}</text>
			</view>

			<!-- 换件 -->
			<view class="addrepair-card__switch" v-if="IsCheckReplacement">
				<text>换件</text>
				<switch color="#3d85db" :disabled="switchReplacePart" :checked="switchReplacePart" @change="switchReplacePart=$event.detail.value" />
			</view>

			<AGInput :required="IsRequiredFailurePart" :value="faultPartItem.PartsNum" dropdown readonly placeholder="故障件"
			 @dropDownClick="faultPartClick('fault',$event)" />
			<view class="addrepair-card__tip">
				故障件：{{faultPartItem.PartsName||''}}
			</view>
			<view class="addrepair-card__tags">
				<view class="ag-status-tag primary"><text style="font-size: 18px;">保修件: {{faultPartItem.IsWarranty ? '是' : '否'}}</text></view>
				<view class="ag-status-tag primary"><text style="font-size: 18px;">保内保外: {{faultPartItem.InOrOffWarranty | displayOrOffWarranty}}</text></view>
			</view>
			<view class="ag-spacer30"></view>
			<block v-if="switchReplacePart">
				<AGInput :required="IsRequiredFailurePart" :value="changeFaultPartItem.PartsNum" dropdown readonly placeholder="更换件"
				 @dropDownClick="faultPartClick('replace',$event)" />
				<view class="addrepair-card__tip">
					更换件：{{changeFaultPartItem.PartsName||''}}
				</view>
				<view class="addrepair-card__pictags">
					<image :src="changeFaultPartItem.base64Img" />
					<view>
						<view class="ag-status-tag primary"><text style="font-size: 18px;">零售价: {{changeFaultPartItem.Price||'0'}}</text></view>
						<view class="ag-status-tag primary"><text  style="font-size: 18px;">网点库存: {{changeFaultPartItem.SiteStock ||'0'}}</text></view>
						<view class="ag-status-tag primary"><text  style="font-size: 18px;">换件保修(月): {{changeFaultPartItem.WarrantyPeriodOfRep ||'0'}}</text></view>
					</view>
				</view>
			</block>

			<view class="ag-divider"></view>
			<!-- 保内转保外 -->
			<view class="addrepair-card__switch" v-if="faultPartItem.InOrOffWarranty">
				<text v-if="faultPartItem.InOrOffWarranty==1">保外转保内</text>
				<text v-if="faultPartItem.InOrOffWarranty==2">保内转保外</text>
				<switch color="#3d85db" :checked="isReasonShow" @change="onSwitch" />
			</view>

			<picker mode="selector" :range="ReasonData" :value="ReasonCodeId" range-key="Name" @change="ChangeReason">
				<AGInput dropdown readonly placeholder="原因代码" v-if="isReasonShow" :value="ReasonData[ReasonIndex].Name" />
			</picker>

			<AGInput textarea v-if="isShowRemark" :placeholder="RemarkName" @change="ChangeRemark" />
			<view class="addrepair-card__footer">
				<button class="cu-btn lg primary block" @click="onClick">确定</button>
				<button class="cu-btn lg primary block plain" @click="onClose">取消</button>
			</view>
		</view>
		<view class="ag-spacer30"></view>
		<faultreePopup ref="faultreePopup" :faultList="faultInfoList" @faultreeConfirm="faultreeConfirm" @faultreeCancel="faultreeCancel">
			<block v-if="preSelectFaultItemPath && preSelectFaultItemPath.length>0">
				<view slot="head" v-for="(faultItem,findex) in preSelectFaultItemPath" :key="faultItem.RepairFaultId" style="color: #F0AD4E; font-size: 10px;"
				 @click.stop="faultItemClick(faultItem.RepairFaultId, $event)">
					{{faultItem.Name||''}}{{findex!=preSelectFaultItemPath.length-1?'-':''}}
				</view>
			</block>

			<uni-list slot="body">
				<uni-list-item v-for="(faultItem,index) in faultInfoList" :title="faultItem.Name" :key="index" :show-arrow="faultItem.level<5"
				 @click.stop="clickFaultItem(index,$event)">
				</uni-list-item>
			</uni-list>
		</faultreePopup>
	</view>
</template>
<script>
	import addrepairbehavior from './addrepairbehavior'
	import AGInput from '@/components/AGInput'
	import faultreePopup from '@/components/FaultreePopup'
	import uniList from "@dcloudio/uni-ui/lib/uni-list/uni-list.vue"
	import uniListItem from "@dcloudio/uni-ui/lib/uni-list-item/uni-list-item.vue"

	export default {
		components: {
			AGInput,
			faultreePopup,
			uniList,
			uniListItem
		},
		mixins: [addrepairbehavior],
		data() {
			return {
				IsCheckReplacement: false,
				switchReplacePart: false,
				IsRequiredFailurePart: false,
				orderDetailId: '',
				prodItemObj: {},
				faultInfoList: [],
				faultyGroup: '',
				//选择中故障树
				selectFaultItem: {},
				//确认后故障树
				confirmSelectFaultItem: {},
				prodRepInfo: {},
				//故障件信息
				faultPartItem: {},
				//更换件信息
				changeFaultPartItem: {},
				isReasonShow: false,
				//原因列表
				ReasonData: {},
				ReasonIndex: 0,
				Remark: '',
				RemarkName: '备注',
				repairData: {},
				editRepairData: {},
				editRepairIndex: 0,
				Type: 'Add',
				//保内转保外
				IsInWarrantyToOut: false,
				//保内转保外原因ID
				InWarrantyToOutReasonCode: '',
				//保外转保内
				IsOutWarrantyToIn: false,
				//保外转保内原因ID
				OutWarrntyToInReasonCode: '',
				//保内转保外备注
				WarrantyMarks: '',
				//维修备注
				RepairMarks: '',

				isShowRemark: true
			}
		},
		filters: {
			//保内保外显示值
			displayOrOffWarranty(value) {
				if (value) {
					switch (value) {
						case 1:
							return "保外";
						case 2:
							return "保内";
						case 3:
							return "保外转保内";
						default:
							return "";
					}
				} else {
					return "";
				}
			},
		},
		watch: {
			'faultPartItem': {
				handler(newval, oldval) {
					this.setReasonData(newval)
				}
			},
			'switchReplacePart': {
				handler(newval, oldval) {
					if(newval==true){
						this.isShowRemark=false;
					}else{
						this.isShowRemark=true;
					}
				}
			},
		},
		computed: {
			selectFaultItemPath() {
				let faultItem = this.confirmSelectFaultItem;

				let faultNameArray = [];
				faultNameArray.push(faultItem.Name);
				while (faultItem.hasOwnProperty('parentFaultItem')) {
					faultItem = faultItem.parentFaultItem
					faultNameArray.push(faultItem.Name)
				}
				return faultNameArray.reverse().join("--")
			},
			preSelectFaultItemPath() {
				let faultItem = this.selectFaultItem;
				console.log(faultItem)
				let faultNameArray = [];
				faultNameArray.push({
					Name: faultItem.Name,
					RepairFaultId: faultItem.RepairFaultId
				});
				while (faultItem.hasOwnProperty('parentFaultItem')) {
					faultItem = faultItem.parentFaultItem
					faultNameArray.push({
						Name: faultItem.Name,
						RepairFaultId: faultItem.RepairFaultId
					})
				}
				return faultNameArray.reverse()
			}
		},
		onLoad(e) {
			let {
				orderDetailId,
				prodItem,
				editRepairData,
				editRepairIndex,
				Type,
			} = e;
			this.orderDetailId = orderDetailId;
			this.prodItemObj = JSON.parse(decodeURIComponent(prodItem));
			if (Type == "Edit") {
				if (editRepairData && editRepairIndex) {
					this.editRepairData = JSON.parse(decodeURIComponent(editRepairData));
					this.editRepairIndex = editRepairIndex;
					this.Type = Type;
					this.confirmSelectFaultItem = this.editRepairData.confirmSelectFaultItem;
					this.faultPartItem = this.editRepairData.faultPartItem;
					this.changeFaultPartItem = this.editRepairData.changeFaultPartItem;
					this.switchReplacePart = this.editRepairData.switchReplacePart;
					this.isReasonShow = this.editRepairData.isReasonShow;
					this.IsCheckReplacement = this.editRepairData.IsCheckReplacement;
					this.ReasonIndex = this.editRepairData.ReasonIndex;
					this.selectFaultItem = this.editRepairData.selectFaultItem;
					this.IsRequiredFailurePart = this.editRepairData.IsRequiredFailurePart;
					console.log("修改", this.editRepairData);
				}
			}
			//选择配件后
			this.GetAccessoriesRear();
			//console.log(orderDetailId, this.prodItemObj);
		},
		onUnload() {
			uni.$off("faultpartsearch");
		},
		methods: {
			async setReasonData(newval) {
				//保外转保内
				if (newval.InOrOffWarranty == 1) {
					this.ReasonData = await this.ApplySpecialWarrantyReasonCodeListAsync();
				} else if (newval.InOrOffWarranty == 2) {
					this.ReasonData = await this.ExcludeFromWarrantyReasonCodeListAsync();
				}
			},
			//点击确定
			onClick() {
				if (this.selectFaultItem.hasOwnProperty("level") &&
					this.selectFaultItem.level == 5) {
					if (this.IsRequiredFailurePart) {
						if (this.faultPartItem.PartsNum && this.changeFaultPartItem.PartsNum) {
							this.PageJumpValue();
						} else {
							uni.showToast({
								title: "请填写故障件与更换件",
								icon: "none"
							});
						}
					} else {
						this.PageJumpValue();
					}
				} else {
					uni.showToast({
						title: "添加故障信息",
						icon: "none",
						mask: true
					})
				}
			},
			//页面跳转并传值
			PageJumpValue() {
				
				uni.navigateBack({
					delta: 1
				});
				this.SetRepairData();
				console.log(this.repairData);
				uni.$emit("addrepair", {
					'repairData': this.repairData,
					'Type': this.Type,
					'editRepairIndex': this.editRepairIndex
				});
			},
			//选择配件后
			GetAccessoriesRear() {
				uni.$on('faultpartsearch', (data) => {
					console.log("选择故障件");
					console.log(data);
					if (data.type == "fault") {
						this.faultPartItem = data.faultPartItem;
						this.RepairSearchNewPartAsync(data.faultPartItem.PartsNum).then((result) => {
							if (result && result.length > 0) {
								this.GetPagePartImg(result).then((succ) => {
									this.changeFaultPartItem = result[0];
									console.log(this.changeFaultPartItem);
								}, (err) => {
									console.log(err);
								});
							}
						}, (err) => {
							console.log(err);
						});
					} else if (data.type == "replace") {
						this.changeFaultPartItem = data.faultPartItem;
						console.log(this.changeFaultPartItem);
					}
				});
			},

			//赋值给RepairData回传给维修工单
			SetRepairData() {
				if (this.confirmSelectFaultItem) {
					this.repairData.confirmSelectFaultItem = this.confirmSelectFaultItem;
				}
				if (this.selectFaultItem) {
					this.repairData.selectFaultItem = this.selectFaultItem;
				}
				if (this.faultPartItem) {
					this.repairData.faultPartItem = this.faultPartItem;
				}
				if (this.changeFaultPartItem) {
					this.repairData.changeFaultPartItem = this.changeFaultPartItem;
				}
				this.repairData.switchReplacePart = this.switchReplacePart;
				this.repairData.isReasonShow = this.isReasonShow;
				this.repairData.IsCheckReplacement = this.IsCheckReplacement;
				this.repairData.ReasonIndex = this.ReasonIndex;
				this.repairData.IsRequiredFailurePart = this.IsRequiredFailurePart;
				// IsInWarrantyToOut
				if (this.faultPartItem.InOrOffWarranty == 1) {
					this.repairData.OutWarrntyToInReasonCode = this.ReasonData[this.ReasonIndex].value;
				} else if (this.faultPartItem.InOrOffWarranty == 2) {
					this.repairData.OutWarrntyToInReasonCode = this.ReasonData[this.ReasonIndex].value;
				}

				this.repairData.faultyGroup = this.faultyGroup;

				this.repairData.IsOutWarrantyToIn = this.IsOutWarrantyToIn;
				this.repairData.IsInWarrantyToOut = this.IsInWarrantyToOut;
				this.repairData.RepairMarks = this.RepairMarks;
				this.repairData.WarrantyMarks = this.WarrantyMarks;
			},

			//修改备注
			ChangeRemark(e) {
				this.Remark = e;
				if (this.isReasonShow == true) {
					this.WarrantyMarks = this.Remark;
				} else {
					this.RepairMarks = this.Remark;
				}
				console.log(this.Remark);
			},
			//点击取消
			onClose() {
				uni.navigateBack({
					delta: 1
				});
			},
			//修改原因
			ChangeReason(e) {
				this.ReasonIndex = e.detail.value;
			},
			faultItemClick(faultItemId, e) {
				let faultItem = this.selectFaultItem;
				while (faultItem.parentFaultItem) {
					if (faultItem.RepairFaultId == faultItemId) {
						this.selectFaultItem = faultItem.parentFaultItem;
						this.confirmSelectFaultItem = faultItem.parentFaultItem;
						this.showSubFault(this.selectFaultItem)
						break;
					}
					faultItem = faultItem.parentFaultItem;
				}
				if (!faultItem.hasOwnProperty('parentFaultItem')) {
					this.selectFaultItem = {};
					this.confirmSelectFaultItem = {};
					this.initFaultree();
				}
				console.log(faultItem, e);
			},
			replacePartChange(e) {
				console.log(e);
			},

			//保外转保内-单选框
			onSwitch(e) {
				let isSwitch = e.target.value;
				this.isReasonShow = isSwitch;
				if (isSwitch == true) {
					if (this.faultPartItem.InOrOffWarranty == 1) {
						this.RemarkName = "保外转保内的备注";
						this.IsOutWarrantyToIn = true;
					} else if (this.faultPartItem.InOrOffWarranty == 2) {
						this.RemarkName = "保内转保外的备注";
						this.IsInWarrantyToOut = true;
					}
				} else {
					this.RemarkName = "备注";
				}
			},

			faultPartClick(type, e) {
				if (this.selectFaultItem.hasOwnProperty("level") &&
					this.selectFaultItem.level == 5) {
					uni.navigateTo({
						url: `../wocomplete/faultpartsearch/faultpartsearch?type=${type}`
					})
				} else {
					uni.showToast({
						title: "添加故障信息",
						icon: "none",
						mask: true
					})
				}
			},
			clickFaultItem(index, e) {
				let faultItem = this.faultInfoList[index];
				if (faultItem.level == 1) {
					this.getSubFault(faultItem, "ggd_faultdepict")
				} else if (faultItem.level == 2) {
					this.getSubFault(faultItem, "ggd_defectzone")
				} else if (faultItem.level == 3) {
					this.getSubFault(faultItem, "ggd_diagnosecode")
				} else if (faultItem.level == 4) {
					this.getSubFault(faultItem, "ggd_solution")
				} else if (faultItem.level == 5) {
					this.$refs.faultreePopup.closePoPup();
					this.isShowRemark = true;
					this.confirmSelectFaultItem = faultItem;
					this.IsCheckReplacement = faultItem.IsCheckReplacement;
					this.IsRequiredFailurePart = faultItem.IsRequiredFailurePart;
					this.switchReplacePart = this.IsCheckReplacement;
				}
				this.selectFaultItem = faultItem;
				console.log(faultItem);
			},
			showSubFault(faultItem) {
				if (faultItem.level == 1) {
					this.getSubFault(faultItem, "ggd_faultdepict")
				} else if (faultItem.level == 2) {
					this.getSubFault(faultItem, "ggd_defectzone")
				} else if (faultItem.level == 3) {
					this.getSubFault(faultItem, "ggd_diagnosecode")
				} else if (faultItem.level == 4) {
					this.getSubFault(faultItem, "ggd_solution")
				}
			},
			showFaultTree(e) {
				// this.$refs.faultreePopup.openPoPup();
				this.$nextTick(() => {
					this.initFaultree();
				})

			},
			initFaultree() {
				uni.showLoading({
					mask: true
				});
				this.getProdRepairInfo().then((succ) => {
						if (succ) {
							let {
								faultInfoList,
								prodRepInfo
							} = succ;
							this.faultInfoList = faultInfoList;
							console.log(faultInfoList)
							this.prodRepInfo = prodRepInfo;
						    uni.hideLoading();
							if(this.faultInfoList){
								this.isShowRemark = false;
								this.$refs.faultreePopup.openPoPup();
							}
						}else{
							uni.hideLoading();
						}
					    
					},
					(err) => {
						uni.hideLoading();
					});
			},
			async getProdRepairInfo() {
				let prodRepInfo = await this.productInfoAsync();
				if (prodRepInfo.FaultyGroup && prodRepInfo.FaultyGroup != '') {
					let faultyGroup = prodRepInfo.FaultyGroup;
					this.faultyGroup = faultyGroup;
					let tempFaultInfoList = await this.repairFaultInfoListAsync(faultyGroup);
					for (let faultIndex in tempFaultInfoList) {
						tempFaultInfoList[faultIndex].level = 1;
					}
					
					return {
						faultInfoList: tempFaultInfoList,
						prodRepInfo: prodRepInfo
					}
				} else {
					// this.$refs.faultreePopup.closePoPup();
					uni.showToast({
						title: "该产品没有故障组",
						icon: "none"
					});
					return null;
				}

			},

			async getSubFault(faultItem, filterId) {
				let faultyGroup = faultItem.RepairFaultId;

				let subFaultInfoList = await this.repairFaultInfoListAsync(faultyGroup, filterId);
				for (let faultIndex in subFaultInfoList) {
					subFaultInfoList[faultIndex].parentFaultItem = faultItem;
					subFaultInfoList[faultIndex].level = faultItem.level + 1;
				}
				if (subFaultInfoList && subFaultInfoList.length > 0)
					this.faultInfoList = subFaultInfoList;
			},
			
			faultreeConfirm(e){
				
				this.isShowRemark=true;
			},
			
			faultreeCancel(e) {
				this.isShowRemark=true;
			},



		}
	}
</script>
<style lang="scss">
	@import "./index.scss";
</style>
